import { remToPixels } from '../../utils/dom'

/*
 https://github.com/shiye515/vue-sticky
 */
export default {
  props: {
    top: {
      type: [Number, String],
      default: 0
    },
    zIndex: {
      type: Number,
      default: 10
    }
  },
  data () {
    var top = this.top
    if (String(top).endsWith('rem')) {
      top = remToPixels(top)
    }
    return {
      stickyHeight: 0,
      parsedTop: top,
      position: 'static',
      child: null
    }
  },
  watch: {
    position (cur) {
      var style = {
        position: cur
      }
      switch (cur) {
        case 'sticky':
          style.position = 'fixed'
          style.right = 0
          style.left = 0
          style.top = this.parsedTop + 'px'
          break
        case 'absolute':
          style.position = 'absolute'
          style.right = '0px'
          style.top = 'auto'
          break
        default:
          style.position = 'static'
      }
      this.child.style = style
    }
  },
  methods: {
    scrollHandler () {
      let offset = this.$el.getBoundingClientRect()
      let poffset = this.$el.parentElement.getBoundingClientRect()
      // 元素原本的位置在 sticky 位置下面
      let isStatic = offset.top > this.parsedTop
      // 父元素位置在 viewport 位置上面
      let isAbsolute = poffset.bottom < this.parsedTop + this.stickyHeight
      if (isStatic) {
        this.position = 'static'
      }
      else if (isAbsolute) {
        this.position = 'absolute'
      }
      else {
        this.position = 'sticky'
      }
    }
  },
  render (h) {
    var {parsedTop, bottom, zIndex} = this
    return h('div', {class: 'sticky', style: {top: parsedTop + 'px', bottom, zIndex}}, this.$slots.default)
  },
  mounted () {
    // 保证 this.$el 已经插入文档
    let computedStyle = window.getComputedStyle(this.$el)
    let position = computedStyle.position
    let stickySupport = position.indexOf('sticky') > -1
    let child = this.$el.firstElementChild

    if (!stickySupport && child) {
      this.child = child
      child.style.zIndex = this.zIndex
      this.stickyHeight = parseFloat(computedStyle.height)
      this.$el.style.position = 'static'
      this.$el.style.height = computedStyle.height
      window.addEventListener('scroll', this.scrollHandler, true)
      this.scrollHandler()
    }
  }
}
